package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
     private static  final  long twepoch = 1704067200L; // 2024-01-01 00:00:00
   @Autowired
    private StringRedisTemplate stringRedisTemplate;
   //序列号占用的位数
    private static  final  int COUNT_BITS = 32;
    public  long nextId(String keyPrefix) {
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long epochSecond = now.toEpochSecond(ZoneOffset.UTC);
            long timetamp =epochSecond-twepoch;
        //生成序列号
        String format = now.format(DateTimeFormatter.ofPattern("yyyy:mm:dd"));
        Long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + format);
        //拼接并返回
        return timetamp<<COUNT_BITS|increment;
    }

    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2024, 1, 1, 0, 0, 0);
        long epochSecond = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("second: "+epochSecond);

    }
}
